package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.util.JavaScriptUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 营业额统计
     * @param begin
     * @param end
     */
    @Override
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {

        //创建一个时间集合来装开始到结束得每天
        List<LocalDate> localDates = new ArrayList<>();
        //将第一天先装进去
        localDates.add(begin);
        //创建循环循环每天得日期装进去
        while (!begin.equals(end)){
            //调用方法计算开始日期没加一天就放进集合里面
            begin = begin.plusDays(1);
            localDates.add(begin);
        }

        //创建一个集合来装查询出来的每天的营业额
        List<Double> list = new ArrayList<>();
        //循环每天得集合然后查询每天的营业额
        for (LocalDate localDate : localDates) {
            //调用Api将年月日补充到年月日的这一天最小的时分秒和最大的时分秒
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //使用Map来装Mapper需要的参数
            Map map = new HashMap();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            //因为可能会有一天查不出来是null所以使用三元原算法，等于null就让他是0.0
            turnover = turnover == null ? 0.0 : turnover;
            list.add(turnover);
        }


        return TurnoverReportVO.builder()
                //调用Api将集合以”，“号分割成字符串拼接
                .dateList(StringUtils.join(localDates,","))
                .turnoverList(StringUtils.join(list,","))
                .build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {

        //创建时期集合来装开始到结束的每天日期
        List<LocalDate> localDates = new ArrayList<>();
        localDates.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            localDates.add(begin);
        }
        //创建总量集合来装总人员
        //
        List<Integer> totalUserList = new ArrayList<>();
        //创建新增集合来装每日新增人员
        List<Integer> newUserList = new ArrayList<>();

        for (LocalDate local : localDates) {
            LocalDateTime beginTime = LocalDateTime.of(local, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(local, LocalTime.MAX);

            Integer newList = map(beginTime, endTime);
            Integer totalList = map(null, endTime);

            totalUserList.add(totalList);
            newUserList.add(newList);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(localDates,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    /**
     * 用户统计中调用的map集合抽取出来的方法
     * @param begin
     * @param end
     * @return
     */
    public Integer map(LocalDateTime begin,LocalDateTime end){
        Map map = new HashMap();
        map.put("beginTime",begin);
        map.put("endTime",end);
        return userMapper.countByMap(map);
    }


    /**
     * top10统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //第一种，比较繁琐
        /*------------------------------------------------
        List<String> name = new ArrayList<>();
        List<Integer> number = new ArrayList<>();
        List<GoodsSalesDTO> goodsSalesDTOS = orderMapper.getTop10(beginTime,endTime);
        for (GoodsSalesDTO goodsSalesDTO : goodsSalesDTOS) {
            name.add(goodsSalesDTO.getName());
            number.add(goodsSalesDTO.getNumber());
        }

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(name,","))
                .numberList(StringUtils.join(number,","))
                .build();
                ----------------------------------------------*/


        //第二种，简便
        //因为查出来的是很多的名字和份数，而且是分组查询，所以封装在DTO里面
        List<GoodsSalesDTO> goodsSalesDTOS = orderMapper.getTop10(beginTime,endTime);

        //调用stream流的map方法获取集合泛型里面的属性，然后将这些属性可以重新封装成对象使用的是collect方法
        List<String> name = goodsSalesDTOS.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> number = goodsSalesDTOS.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(name,","))
                .numberList(StringUtils.join(number,","))
                .build();
    }

    /**
     * 订单统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> localDates = new ArrayList<>();
        localDates.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            localDates.add(begin);
        }

        List<Integer> order = new ArrayList<>();
        List<Integer> validOrder = new ArrayList<>();
        for (LocalDate localDate : localDates) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Integer orderCount = os(beginTime,endTime,null);
            orderCount = orderCount == null ? 0:orderCount;

            Integer validOrderCount = os(beginTime, endTime, Orders.COMPLETED);
            validOrderCount = validOrderCount == null ? 0:validOrderCount;

            order.add(orderCount);
            validOrder.add(validOrderCount);
        }

        Integer orderSum = order.stream().mapToInt(Integer::intValue).sum();

        Integer validOrderSum = validOrder.stream().mapToInt(Integer::intValue).sum();

        Double Rate = 0.0;
        if (orderSum != 0){
            Rate = validOrderSum.doubleValue() / orderSum;
        }


        return OrderReportVO.builder()
                .dateList(StringUtils.join(localDates,","))
                .orderCountList(StringUtils.join(order,","))
                .validOrderCountList(StringUtils.join(validOrder,","))
                .totalOrderCount(orderSum)
                .validOrderCount(validOrderSum)
                .orderCompletionRate(Rate)
                .build();
    }

    /**
     * 被订单统计接口调用的传参方法抽离
     * @param beginTime
     * @param endTime
     * @param status
     * @return
     */
    private Integer os(LocalDateTime beginTime, LocalDateTime endTime,Integer status){
        Map map = new HashMap();
        map.put("status",status);
        map.put("beginTime",beginTime);
        map.put("endTime",endTime);
        return orderMapper.ordersStatistics(map);
    }




    /**
     * 导出Excel文件
     * @param response
     */
    @Override
    public void getExcelExport(HttpServletResponse response) {
        //获取近一个月的区间时间
        //往后减三十天
        LocalDate localDateBegin = LocalDate.now().minusDays(30);
        LocalDateTime beginTime = LocalDateTime.of(localDateBegin, LocalTime.MIN);
        //往后减一天，不设置到今天是因为今天有可能还没有结束
        LocalDate localDateEnd = LocalDate.now().minusDays(1);
        LocalDateTime endTime = LocalDateTime.of(localDateEnd, LocalTime.MAX);
        //获取营业统计数据
        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);

        //获取类的加载器来通过POI将数据写入到excel文件中
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //创建一个新的excel报表
            XSSFWorkbook sheets = new XSSFWorkbook(is);
            //获取报表中第一页（根据索引）
            XSSFSheet sheet = sheets.getSheetAt(0);
            //获取需要补充的数据位置(行和单元格)并且填充数据
            sheet.getRow(1).getCell(1).setCellValue("日期为:" + localDateBegin + "至" + localDateEnd);
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());


            //将所有日期放在一个集合里面
            List<LocalDate> localDates = new ArrayList<>();
            localDates.add(localDateBegin);
            while (!localDateBegin.equals(localDateEnd)){
                localDateBegin = localDateBegin.plusDays(1);
                localDates.add(localDateBegin);
            }

            //定义变量为7，因为是从第七行开始写的，所以后面在循环里面7++
            int dt = 7;
            for (LocalDate date : localDates) {
                LocalDateTime begin = LocalDateTime.of(date, LocalTime.MIN);
                LocalDateTime end = LocalDateTime.of(date, LocalTime.MAX);
                BusinessDataVO vo = workspaceService.getBusinessData(begin, end);
                LocalDate localDate = begin.toLocalDate();
                sheet.getRow(dt).getCell(1).setCellValue(localDate.toString());
                sheet.getRow(dt).getCell(2).setCellValue(vo.getTurnover());
                sheet.getRow(dt).getCell(3).setCellValue(vo.getValidOrderCount());
                sheet.getRow(dt).getCell(4).setCellValue(vo.getOrderCompletionRate());
                sheet.getRow(dt).getCell(5).setCellValue(vo.getUnitPrice());
                sheet.getRow(dt).getCell(6).setCellValue(vo.getNewUsers());

                dt++;
            }

            //通过Http获取文件输出流
            ServletOutputStream stream = response.getOutputStream();
            //将创建出来的excel报表写入
            sheets.write(stream);

            //为了写入更快
            stream.flush();
            //释放资源
            stream.close();
            sheets.close();
            is.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
